package com.zyzg.filter;

import com.alibaba.fastjson2.JSONObject;
import com.zyzg.utils.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证过滤器
 */
@Component
public class AppAuthFilter implements Filter {
    @Autowired
    private RedisCache redisCache;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String appId = httpRequest.getHeader("appid");
        String appSecret = httpRequest.getHeader("appsecret");

        if (appId != null && appSecret != null) {
            String storedAppSecret = redisCache.getCacheObject(appId);
            if (storedAppSecret != null && storedAppSecret.equals(appSecret)) {
                chain.doFilter(request, response);
                return;
            }
        }
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.setContentType("application/json");
        httpResponse.setCharacterEncoding("UTF-8");

        JSONObject responseJson = new JSONObject();
        responseJson.put("code", 401);
        responseJson.put("message", "密钥错误或参数不正确");
        httpResponse.getWriter().write(responseJson.toJSONString());
    }
}